import {api} from "@/utils/api";
import type {Ref} from "vue";

// 获取轮播图数据
export async function fetchCarouselData(carouselImages: Ref<any[]>) {
    try {
        const carouselData = await api.getCarousel();
        if (carouselData && carouselData.code === 1) {
            carouselImages.value = await Promise.all(
                carouselData.data.map(async (item: any) => ({
                    imageUrl: item.name
                        ? await api.getResourceByPath(item.name)
                        : "@/public/pictures/no_image_available.jpeg"
                }))
            );
        } else {
            ElMessage.error(carouselData?.msg || "获取轮播图数据时发生未知错误");
        }
    } catch (error) {
        ElMessage.error("加载轮播图数据时发生错误");
    }
}

// 获取最新捐赠滚动展示数据
export async function fetchScrollData(scrollRenderData: Ref<string>) {
    try {
        const data = await api.getNewsCenterById(20);
        if (data && data.code === 1) {
            scrollRenderData.value = data.data.details;
        } else {
            ElMessage.error(data?.msg || "获取最新捐赠数据时发生未知错误");
        }
    } catch (error) {
        ElMessage.error("加载最新捐赠数据时发生错误");
    }
}

// 获取通用新闻列表
export async function fetchNewsData(category: string, stateRef: Ref<any[]>) {
    try {
        const data = await api.getNewsCenterPage(category, 1, 8);
        if (data && data.code === 1) {
            stateRef.value = data.data.content;
        } else {
            ElMessage.error(`获取${category}数据失败: ${data?.msg || "发生未知错误"}`);
        }
    } catch (error) {
        ElMessage.error(`加载${category}数据时发生错误`);
    }
}

// 获取带图片的新闻列表
export async function fetchNewsWithImages(
    category: string,
    stateRef: Ref<any[]>,
    formatDate: (dateString: string) => string
) {
    try {
        const data = await api.getNewsCenterPage(category, 1, 8);
        if (data && data.code === 1) {
            for (let item of data.data.content) {
                item.imageUrl = item.pic
                    ? await api.getResourceByPath(item.pic)
                    : "@/public/pictures/no_image_available.jpeg";
                item.updateTime = formatDate(item.updateTime);
            }
            stateRef.value = data.data.content;
        } else {
            ElMessage.error(`获取带图片的${category}数据失败`);
        }
    } catch (error) {
        ElMessage.error(`加载带图片的${category}数据时发生错误`);
    }
}

// 获取捐赠名单新闻列表
export async function fetchDonationListData(stateRef: Ref<any[]>) {
    try {
        const data = await api.getNewsTypeList("捐赠名单（内部导航，不显示）");
        let typeList: string[] = [];
        let articleList: Article[] = [];
        if (data && data.code === 1) {
            typeList = data.data.map((item: Category) => item.type2);
            articleList.push(...(await Promise.all(
                typeList.map(async (category: string): Promise<Article[]> => {
                    const response = await api.getNewsCenterPage(category, 1, 10);
                    if (response && response.code === 1) {
                        return response.data.content;
                    } else {
                        return [];
                    }
                })
            )).flat())
            stateRef.value = articleList.slice(0, 8);
        } else {
            ElMessage.error("获取捐赠名单导航分类失败");
        }
    } catch (error) {
        ElMessage.error("加载捐赠名单数据时发生错误");
    }
}

// 格式化日期
export function formatDate(dateString: string): string {
    const date = new Date(dateString);
    return `${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
}
